package com.samsung.controller.vote;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.samsung.common.annotation.LoginAjaxAuth;
import com.samsung.common.annotation.LoginAuth;
import com.samsung.common.util.BaseExcelUtil;
import com.samsung.common.util.BaseUtil;
import com.samsung.common.util.Constant;
import com.samsung.dto.vote.CreateVoteDto;
import com.samsung.dto.vote.VoteActionDto;
import com.samsung.dto.vote.VoteDetailDto;
import com.samsung.model.common.Page;
import com.samsung.model.user.User;
import com.samsung.model.vote.VoteTopic;
import com.samsung.service.vote.CreateVoteService;
import com.samsung.service.vote.TopicService;
import com.samsung.service.vote.UpdateVoteService;
import com.samsung.service.vote.VoteHistoryService;
import com.samsung.service.vote.VoteService;
/**
 * @ClassName CreateVoteController
 * @Description 新建投票的Controller
 * 
 * @author c3.Zhang 
 * @date 2015/4/22 11:00:00
 */

@Controller
@RequestMapping("/vote")
@SessionAttributes(Constant.LOGIN_TOKEN)
public class VoteController {

	@Resource
	private CreateVoteService createVoteService; 
	@Resource
	private UpdateVoteService updateVoteService;
	@Autowired
	private VoteService voteService;
	@Autowired
	private TopicService topicService;
	@Autowired
	private VoteHistoryService voteHistoryService;
	
	/**
	 * @Title toCreateVote
	 * @Description 控制主页的新建投票跳转到对应页面
	 * 
	 * @return ModelAndView
	 */
	@RequestMapping("createPage")
	@LoginAuth
	public ModelAndView toCreateVote() {
		return new ModelAndView("vote/newVote");
	}
	
	/********************* 这次新增的start*********************/
	
	/**
	 * 新建投票
	 * @return
	 */
	@RequestMapping("addVote")
	@LoginAuth
	public ModelAndView addVote() {
		return new ModelAndView("vote/addVote");
	}
	
	/**
	 * 投票列表
	 * @return
	 */
	@RequestMapping("voteList")
	public ModelAndView voteList() {
		return new ModelAndView("vote/voteList");
	}
	
	/**
	 * custom 投票列表
	 * @return
	 */
	@RequestMapping("ctVoteList")
	public ModelAndView ctVoteList( HttpServletRequest request ) {
		return new ModelAndView("vote/ctVoteList");
	}
	/**
	 * 我参与的投票
	 * @return
	 */
	@RequestMapping("myJoin")
	@LoginAuth
	public ModelAndView myJoin() {
		return new ModelAndView("vote/myJoin");
	}
	
	/**
	 * 
	 * title check
	 * @return
	 */
	@RequestMapping("checkTitle")
	@LoginAjaxAuth
	@ResponseBody
	public Map<String, Object> checkTitle( @RequestParam("title") String title ){
		Map<String, Object> model = new HashMap<String, Object>();
		model = createVoteService.checkTitle(title);
		return model;
	}
	
	/**
	 * save new vote
	 * @return
	 */
	@RequestMapping("saveVote")
	@LoginAjaxAuth
	@ResponseBody
	public Map<String, Object> saveVote( VoteTopic topic,CreateVoteDto createVoteDto, @ModelAttribute(Constant.LOGIN_TOKEN) User user){
		Map<String, Object> model = new HashMap<String, Object>();
		model = createVoteService.saveTopic(topic, createVoteDto, user);
		return model;
	}
	/**
	 * 我发起的投票
	 * @return
	 */
	@RequestMapping("myCreate")
	@LoginAuth
	public ModelAndView myCreate() {
		return new ModelAndView("vote/myCreate");
	}
	
	/**
	 * 获取投票主题信息
	 * @param tid
	 * @return
	 */
	@RequestMapping("getVoteDetail")
//	@LoginAjaxAuth
	@ResponseBody
	public List<Map<String, Object>> getVoteDetail(String tid){
		return voteHistoryService.getVoteDetail(tid);
	}
	/**
	 * 投票action
	 */
	@RequestMapping("voteAction")
	@LoginAjaxAuth
	@ResponseBody
	public Map<String, String>checkVoteDetail(VoteActionDto voteActionDto, @ModelAttribute(Constant.LOGIN_TOKEN) User user, HttpServletRequest request){
		String ip = BaseUtil.getRemoteHost(request);
		voteActionDto.setIp(ip);
		voteActionDto.setUid(user.getUid());
		return voteHistoryService.saveVoteAction(voteActionDto);
	}
	
	/**
	 * custom 投票action
	 */
	@RequestMapping("ctVoteAction")
	@ResponseBody
	public Map<String, String>ctCheckVoteDetail(VoteActionDto voteActionDto, HttpServletRequest request){
		String ip = BaseUtil.getRemoteHost(request);
		voteActionDto.setIp(ip);
		voteActionDto.setUid("");
		return voteHistoryService.saveVoteAction(voteActionDto);
	}
	/**
	 * 获取投票列表数据(包括游客，因此不加登录校验)
	 * @param search_title
	 * @param startDate
	 * @param endDate
	 * @param currentPage
	 * @param request
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("voteListData")
	@ResponseBody
	public Map<String, Object> getVoteList(String search_title,String startDate,String endDate,Integer currentPage,HttpServletRequest request,HttpSession session) {
		Map<String, Object> condition =  new HashMap<String, Object>();
		User user = (User)session.getAttribute(Constant.LOGIN_TOKEN);
		String ip = BaseUtil.getRemoteHost(request);
		condition.put("ip", ip);
		if( user != null ){
			condition.put("uid", user.getUid());
		}
		condition.put("search_title", search_title);
		condition.put("startDate", startDate);
		condition.put("endDate", endDate);
		Integer totalCount = topicService.getVoteCount(condition);
		Page page = new Page(totalCount, currentPage);
		condition.put("page", page);
		List<Map<String, Object>> resultMap = topicService.getVoteList(condition);
		Map<String, Object> reMap = new HashMap<String, Object>();
		reMap.put("resultMap", resultMap);
		reMap.put("page", page);
		return reMap;
	}
	
	/**
	 * 获取我参与的投票列表数据
	 * @param search_title
	 * @param startDate
	 * @param endDate
	 * @param currentPage
	 * @param session
	 * @return
	 */
	@RequestMapping("myJoinListData")
	@LoginAjaxAuth
	@ResponseBody
	public Map<String, Object> getMyJoinList(String search_title,String startDate,String endDate,Integer currentPage,HttpSession session,HttpServletRequest request){
		Map<String, Object> condition =  new HashMap<String, Object>();
		User user = (User)session.getAttribute(Constant.LOGIN_TOKEN);
		String ip = BaseUtil.getRemoteHost(request);
		condition.put("ip", ip);
		condition.put("uid", user.getUid());
		condition.put("search_title", search_title);
		condition.put("startDate", startDate);
		condition.put("endDate", endDate);
		Integer totalCount = topicService.getMyJoinCount(condition);
		Page page = new Page(totalCount, currentPage);
		condition.put("page", page);
		List<Map<String, Object>> resultMap = topicService.getMyJoinList(condition);
		Map<String, Object> reMap = new HashMap<String, Object>();
		reMap.put("resultMap", resultMap);
		reMap.put("page", page);
		return reMap;
	}
	
	/**
	 * 获取我发起的投票列表数据
	 * @param search_title
	 * @param startDate
	 * @param endDate
	 * @param currentPage
	 * @param session
	 * @return
	 */
	@RequestMapping("myCreateListData")
	@LoginAjaxAuth
	@ResponseBody
	public Map<String, Object> myCreateList(String search_title,String startDate,String endDate,Integer currentPage,HttpSession session,HttpServletRequest request){
		Map<String, Object> condition =  new HashMap<String, Object>();
		User user = (User)session.getAttribute(Constant.LOGIN_TOKEN);
		String ip = BaseUtil.getRemoteHost(request);
		condition.put("ip", ip);
		condition.put("uid", user.getUid());
		condition.put("search_title", search_title);
		condition.put("startDate", startDate);
		condition.put("endDate", endDate);
		Integer totalCount = topicService.getMyCreateCount(condition);
		Page page = new Page(totalCount, currentPage);
		condition.put("page", page);
		List<Map<String, Object>> resultMap = topicService.getMyCreateList(condition);
		Map<String, Object> reMap = new HashMap<String, Object>();
		reMap.put("resultMap", resultMap);
		reMap.put("page", page);
		return reMap;
	}
	
	
	@RequestMapping("ctVoteDetail")
	public ModelAndView ctVoteDetail(String topicId){
		ModelAndView mav = new ModelAndView("vote/ctVoteDetail");
		List<VoteDetailDto> voteDetail = voteHistoryService.getVoteDetailCt(topicId);
		mav.addObject("voteDetail",voteDetail);
		return mav;
	}
	
	
	@RequestMapping("voteDetail")
	@LoginAuth
	public ModelAndView VoteDetail(String topicId){
		ModelAndView mav = new ModelAndView("vote/voteDetail");
		List<VoteDetailDto> voteDetail = voteHistoryService.getVoteDetailCt(topicId);
		mav.addObject("voteDetail",voteDetail);
		return mav;
	}
	
	@RequestMapping("delete")
	@LoginAjaxAuth
	@ResponseBody
	public Map<String, String> deleteVoteData(String tid){
		return voteService.deleteVoteRecord(tid);
	}
	
	@RequestMapping("updateVoteDetail")
	@LoginAuth
	public ModelAndView updateVoteDetail( String tid ){
		ModelAndView mav = new ModelAndView("vote/updateVoteDetail");
		mav.addObject("voteDetail", updateVoteService.getVoteDetail(tid));
		return mav;
	}
	
	@RequestMapping("beforeUpdate")
	@LoginAjaxAuth
	@ResponseBody
	public Map<String, String> checkVoteCount(String tid){
		return updateVoteService.getVoteCount(tid);
	}
	
	@RequestMapping("/exportExcel")
	@LoginAjaxAuth
	@ResponseBody
	public Map<String, String> exportExcel(String topicId,HttpServletRequest request){
		Map<String, String> map = new HashMap<String, String>();
		List<List<Object>> resultMap = topicService.getVoteResultList(topicId);
		String title = "投票结果";
		String[] rowName = {"投票话题","投票类型","投票范围","singleId","姓名","投票结果","创建时间"};
		String fileName = "投票结果";
		BaseExcelUtil excelUtil = new BaseExcelUtil(title, rowName, fileName, resultMap, request);
		try {
			String filePath = excelUtil.export();
			map.put("filePath", filePath);
			map.put("status", "ok");
		} catch (IOException e) {
			map.put("status", "error");
			e.printStackTrace();
		}
		return map;
	}
	/********************* 这次新增的end*********************/
	
//	/**
//	 * @Title CreateVote
//	 * @Description 控制新建投票的页面跳转和业务处理
//	 * 
//	 * @param VoteTopic 新建投票信息的model
//	 * @param CreateVoteDto 投票信息的中间model
//	 * @param User session中的用户信息
//	 * @return Map 结果集
//	 */
//	@RequestMapping("/create")
//	@LoginAjaxAuth
//	@ResponseBody
//	public Map<String,Object> createVote (VoteTopic topic,CreateVoteDto createVoteDto, @ModelAttribute(Constant.LOGIN_TOKEN) User user) {
//		Map<String,Object> model = new HashMap<String,Object>();
//		model = createVoteService.checkTopicInfo(topic, createVoteDto);
//		if (model.size() == 0) {
//			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//			Date deadLineDate = null;
//			try {
//				deadLineDate = sdf.parse(createVoteDto.getEndTime());
//			} catch (ParseException e) {
//				model.put("message", "投票截止时间日期格式错误");
//				model.put("flag", "failure");
//				return model;
//			}
//			topic.setDeadline(deadLineDate);
//			if (topic.getDeadline().before(new Date())) {
//				model.put("message", "投票截止时间不能为系统时间之前");
//				model.put("flag", "failure");
//				return model;
//			}
//			topic.setUid(user.getUid());
//			topic.setTid(BaseUtil.getUUID());
//			topic.setCreateTime(new Date());
//			topic.setAdvert("upload/3.png");
//			List<VoteOption> optionList = new ArrayList<VoteOption>();
//			optionList = createVoteService.setOptionInfo(topic,createVoteDto);
//			model = createVoteService.checkOptionInfo(optionList);
//			if (model.size() == 0) {
//				createVoteService.saveTopic(topic);
//				createVoteService.saveOption(optionList);
//				model.put("message", "新建成功");
//				model.put("flag", "success");
//				return model;
//			}
//		}
//		return model;
//	}

	/**
	 * @Title checkTitleMap
	 * @Description 标题的blur()事件处理
	 * 
	 * @param title 新建投票的标题
	 * @return Map 结果集
	 */
//	@RequestMapping("/checkTitle")
//	@LoginAjaxAuth
//	@ResponseBody
//	public Map<String,Object> checkTitleMap (@RequestParam("title") String title) {
//		Map<String,Object> checkModel = new HashMap<String,Object>();
//		checkModel = createVoteService.checkTitle(title);
//		return checkModel;
//	}
	
	
	// -------------------------------------------------
	// UpdateVoteController
	// -------------------------------------------------
	@RequestMapping("/checkUpdate")
	@ResponseBody
	@LoginAjaxAuth
	public Map<String, Object> checkUpdateVote(HttpServletRequest request,@ModelAttribute(Constant.LOGIN_TOKEN) User user) {
		String tid = request.getParameter("tid");
		Map<String, Object> modelMap = new HashMap<String, Object>();
		if(updateVoteService.checkTitleData(tid, user.getUid())) {
			modelMap.put("flag", "failure");
			modelMap.put("message", "该话题为别人发起，无法修改！");
		}
		if (!updateVoteService.checkVoteData(tid)) {
			modelMap.put("flag", "failure");
			modelMap.put("message", "该话题正在投票中，无法修改！");
		} else {
			modelMap.put("flag", "success");
		}
		return modelMap;
	}

	@RequestMapping("/updateVotePage")
	@LoginAuth
	public ModelAndView toUpdate(HttpServletRequest request) {
		String tid = request.getParameter("tid");
		ModelAndView mav = new ModelAndView("vote/updateVote");
		VoteTopic topic = updateVoteService.selectTopic(tid);
		CreateVoteDto createVoteDto = updateVoteService.selectOption(tid);
		int count = updateVoteService.countContent(createVoteDto);
		SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		createVoteDto.setEndTime(df.format(topic.getDeadline()));
		mav.addObject("topic", topic);
		mav.addObject("count", count);
		mav.addObject("createVoteDto", createVoteDto);
		return mav;
	}

//	/**
//	 * @Title CreateVote
//	 * @Description 控制新建投票的页面跳转和业务处理
//	 * 
//	 * @param VoteTopic 新建投票信息的model
//	 * @param CreateVoteDto 投票信息的中间model
//	 * @param User session中的用户信息
//	 * @return Map 结果集
//	 */
//	@RequestMapping("/updateVote")
//	@LoginAjaxAuth
//	@ResponseBody
//	public Map<String,Object> CreateVote (VoteTopic topic,CreateVoteDto createVoteDto, @ModelAttribute(Constant.LOGIN_TOKEN) User user,
//			HttpServletRequest request) {
//		Map<String,Object> model = new HashMap<String,Object>();
//		String tid =request.getParameter("tid");
//		model = createVoteService.checkTopicInfo(topic, createVoteDto);
//		if (model.size() == 0) {
//			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//			Date deadLineDate = null;
//			try {
//				deadLineDate = sdf.parse(createVoteDto.getEndTime());
//			} catch (ParseException e) {
//				model.put("message", "投票截止时间日期格式错误");
//				model.put("flag", "failure");
//				return model;
//			}
//			topic.setDeadline(deadLineDate);
//			if (topic.getDeadline().before(new Date())) {
//				model.put("message", "投票截止时间不能为系统时间之前");
//				model.put("flag", "failure");
//				return model;
//			}
//			topic.setUid(user.getUid());
//			topic.setCreateTime(new Date());
//			topic.setAdvert("upload/3.png");
//			List<VoteOption> optionList = new ArrayList<VoteOption>();
//			optionList = createVoteService.setOptionInfo(topic,createVoteDto);
//			model = createVoteService.checkOptionInfo(optionList);
//			if (model.size() == 0) {
//				if (!updateVoteService.checkVoteData(tid)) {
//					model.put("code", "failure");
//					model.put("message", "该话题正在被投票中，无法删除！");
//				} else {
//					model = updateVoteService.deleteVoteRecord(tid);
//					createVoteService.saveTopic(topic);
//					createVoteService.saveOption(optionList);
//					model.put("message", "修改成功");
//					model.put("flag", "success");
//					return model;
//				}
//			}
//		}
//		return model;
//	} 

	/**
	 * @Title checkTitleMap
	 * @Description 标题的blur()事件处理
	 * 
	 * @param title 新建投票的标题
	 * @param 
	 * @return Map 结果集
	 */
	@RequestMapping("checkUpdateTitle")
	@LoginAjaxAuth
	@ResponseBody
	public Map<String,Object> checkTitleMap (@RequestParam("title") String title, @RequestParam("compareName") String compareName) {
		Map<String,Object> checkModel = new HashMap<String,Object>();
		checkModel = updateVoteService.checkTitle(title, compareName);
		return checkModel;
	}
	
	
	// -----------------------------------------------------------------
	// 李炯
	// -----------------------------------------------------------------
	@RequestMapping("/list")
	public ModelAndView userList(HttpServletRequest request, HttpServletResponse response){
		ModelAndView mav = new ModelAndView("vote/listVote");
		Map<String, Object> resultMap=new HashMap<String, Object>();
		Map<String, Object> paramMap=new HashMap<String, Object>();
		paramMap=this.operaterParam(request);
		//paramMap.remove("uid");
		 resultMap = voteService.getVoteData(paramMap);
		 mav.addObject("dataMap", resultMap);
		return mav;
	}
	
	@LoginAuth
	@RequestMapping("/myList")
	public ModelAndView myVoteList(HttpServletRequest request, HttpServletResponse response){
		ModelAndView mav = new ModelAndView("vote/listVote");
		Map<String, Object> resultMap=new HashMap<String, Object>();
		Map<String, Object> paramMap=new HashMap<String, Object>();
		paramMap=this.operaterParam(request);
		 resultMap = voteService.getVoteData(paramMap);
		 mav.addObject("dataMap", resultMap);
		return mav;
	}
	
	
	/**
	* @Title: operaterParam
	* @Description: TODO(获取页面传入数据)
	* @param @param request
	* @param @return    设定文件
	* @return Map    返回类型
	* @throws
	*/ 
	public Map<String, Object>  operaterParam(HttpServletRequest request){
		Map<String, Object> paramMap=new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("UTF-8");
			String nPage=request.getParameter("nowPage");
			String select_search=request.getParameter("select_search");
			String title_search=request.getParameter("title_search");
			 
			String uid=request.getParameter("uid");
//			not  use???
//			Object obj=request.getParameter("checkItem");
//			  if(obj instanceof String){
//				  String checkItem   =   (String)   obj;
//			  }else if(obj instanceof Collection){
//				  String[] checkArray=(String[])obj;
//			  }
			paramMap.put("select_search", select_search);
			paramMap.put("uid", uid);
			paramMap.put("nowPage", nPage);
			paramMap.put("title_search", title_search);
		} catch (UnsupportedEncodingException e) {
			return paramMap;
		}
		
		return paramMap;
	}
	
}
